"use client";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { TaskDialog } from "./task-dialog";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { ColDef } from "ag-grid-community";
import { CreateTaskSchema } from "@/schemas";
import * as z from "zod";
import DataGrid from "@/components/data-grid";
import { useSession } from "next-auth/react";
import { CustomCellRendererProps } from "ag-grid-react";
import { toast } from "sonner";
import {
  EnTaskStatus,
  type Task,
  RowActionsHandler,
  EnRowAction,
} from "../../types";
import { AlertDialogDemo } from "@/components/alert";
const headers = { "Content-Type": "application/json" };

const TaskPage = () => {
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [alertDelOpen, setAlertDelOpen] = useState(false);
  const [alertStartOpen, setAlertStartOpen] = useState(false);
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [rowData, setRowData] = useState([]);
  const { data: session } = useSession();
  const user = session?.user;
  const taskQuery = useQuery({
    queryKey: ["tasks", page, pageSize, user],
    queryFn: async () => {
      if (!user) return { page: 0, size: 0, tasks: [] };
      return fetch(
        `/api/task/pagination?page=${page}&size=${pageSize}&userId=${user?.id}`,
        {
          method: "GET",
          //credentials: "include",
          headers: { ...headers },
        },
      ).then((res) => {
        if (res.ok) {
          return res.json();
        } else {
          return { page: 0, size: 0, tasks: [] };
        }
      });
    },
  });
  useEffect(() => {
    if (taskQuery.isPending) return;

    const { page, size, tasks } = taskQuery.data;
    setPage(page);
    setPageSize(size);
    setRowData(tasks);
  }, [taskQuery]);

  if (taskQuery.isPending) return "Loading...";
  const createTask = async (values: z.infer<typeof CreateTaskSchema>) => {
    if (!user?.id) {
      toast.error("user not login or found");
      return;
    }
    const payload = { userId: Number(user?.id), status: "CREATED", ...values };
    try {
      const resp = await fetch("/api/task", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!resp.ok) {
        const errorData = await resp.json();
        toast.error(
          `Task creation failed: ${errorData.message || resp.statusText}`,
        );
        return;
      }
      toast.info("任务创建成功!");
      queryClient.invalidateQueries({ queryKey: ["tasks"] });
      setOpen(false);
    } catch (error) {
      toast.error(
        `Task creation failed: ${error || "An unexpected error occurred."}`,
      );
    }
  };

  const deleteTask = (task: Task) => {
    fetch(`/api/task/${task.id}`, { method: "DELETE" }).then((resp) => {
      if (resp.ok) {
        toast.info(`Delete task ${task.name} successful`);
        queryClient.invalidateQueries({ queryKey: ["tasks"] });
      } else {
        toast.info(`Delete task ${task.name} failed`);
      }
    });
  };
  const startTask = (task: Task) => {
    fetch(`/api/task/start/${task.id}`, { method: "GET" })
      .then((resp) => {
        if (resp.ok) {
          toast.info(`Task ${task.name} start successful`);
        } else {
          toast.error(`Task ${task.name} start failed`);
        }
      })
      .catch((err) => {
        toast.error(`${err}`);
      });
  };
  const stopTask = (task: Task) => {
    fetch(`/api/task/stop/${task.id}`, { method: "GET" }).then((resp) => {
      if (resp.ok) {
        toast.info(`stop task successful ${task.name}`);
        queryClient.invalidateQueries({ queryKey: ["tasks"] });
      } else {
        toast.error(`stop task ${task.name} failed`);
      }
    });
  };
  const actionsHander = (action: EnRowAction, task: Task) => {
    if (action === EnRowAction.START) {
      console.log("start", task.name);

      startTask(task);
    } else if (action === EnRowAction.STOP) {
      console.log("stop", task);
      stopTask(task);
    } else if (action === EnRowAction.DELETE) {
      console.log("delete", task.name);
      deleteTask(task);
    }
  };
  const actionRender = (
    params: CustomCellRendererProps,
    handler: RowActionsHandler<Task>,
  ) => {
    const { data } = params;
    return (
      <div className="flex flex-row">
        {data.status === EnTaskStatus.CREATED ||
        data.status === EnTaskStatus.COMPLETE ? (
          <>
            <AlertDialogDemo
              title={"开始任务?"}
              content={"开始任务"}
              open={alertStartOpen}
              onOpenChange={setAlertStartOpen}
              onCancel={() => {
                setAlertStartOpen(false);
              }}
              onOk={() => {
                setAlertStartOpen(false);
                handler(EnRowAction.START, data);
              }}
            />
            <Button
              variant={"link"}
              onClick={() => {
                setAlertStartOpen(true);
              }}
            >
              Start
            </Button>
          </>
        ) : (
          <Button
            variant={"link"}
            onClick={() => {
              handler(EnRowAction.STOP, data);
            }}
          >
            Stop
          </Button>
        )}
        {data.status !== EnTaskStatus.RUNNING ? (
          <>
            <AlertDialogDemo
              title={"确定删除?"}
              content={"删除后将无法恢复只能重新创建"}
              open={alertDelOpen}
              onOpenChange={setAlertDelOpen}
              onCancel={() => {
                console.log("click cancel");
                setAlertDelOpen(false);
              }}
              onOk={() => {
                setAlertDelOpen(false);
                console.log("click ok");
                handler(EnRowAction.DELETE, data);
              }}
            />
            <Button
              variant={"link"}
              onClick={() => {
                setAlertDelOpen(true);
              }}
            >
              Delete
            </Button>
          </>
        ) : null}
      </div>
    );
  };
  const columnDefs: ColDef[] = [
    { field: "id", headerName: "ID", width: 100 },
    { field: "name", headerName: "Name", flex: 1 },
    { field: "keyword", headerName: "Keyword", flex: 1 },
    { field: "syncData", headerName: "SyncData", flex: 1 },
    { field: "status", headerName: "Status", flex: 1 },
    {
      field: "actions",
      pinned: "right",
      headerName: "Actions",
      flex: 1,
      cellRenderer: (params: CustomCellRendererProps) =>
        actionRender(params, actionsHander),
    },
  ];

  if (taskQuery.error) return "An error has occurred: ";
  return (
    <div className="flex flex-col h-full flex-grow">
      <div className="flex justify-start">
        <TaskDialog
          onSubmitAction={createTask}
          open={open}
          setOpenAction={setOpen}
        />
      </div>
      <DataGrid columnDefs={columnDefs} rowData={rowData} />
    </div>
  );
};
export default TaskPage;
